<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>聊天界面</title>
<link rel="stylesheet" href="layim/dist/css/layui.css">
</head>
<body>
<button id="a1" style="width: 150px;height:50px;display: block;margin-left: 400px" >查看历史记录</button>
<div id="message"></div>
<script src="layim/dist/layui.js"></script>
<script src="./js/jquery-3.2.1.js"></script>
<script>
    //获取url参数
    function getUrlParams(name) { // 不传name返回所有值，否则返回对应值
        var url = window.location.search;
        if (url.indexOf('?') == 1) { return false; }
        url = url.substr(1);
        url = url.split('&');
        var name = name || '';
        var nameres;
        // 获取全部参数及其值
        for(var i=0;i<url.length;i++) {
            var info = url[i].split('=');
            var obj = {};
            obj[info[0]] = decodeURI(info[1]);
            url[i] = obj;
        }
        // 如果传入一个参数名称，就匹配其值
        if (name) {
            for(var i=0;i<url.length;i++) {
                for (const key in url[i]) {
                    if (key == name) {
                        nameres = url[i][key];
                    }
                }
            }
        } else {
            nameres = url;
        }
        // 返回结果
        return nameres;
    }
</script>
<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/websocket");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        //setMessageInnerHTML("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        //setMessageInnerHTML("WebSocket连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        //setMessageInnerHTML("WebSocket连接关闭");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
            if(a==0){
                let con="<li>\n" +
                    "                            <div class=\"layim-chat-user\"><img src=\"http://tp1.sinaimg.cn/5619439268/180/40030060651/1\"><cite><i>"+time()+"</i>"+letterUserName+"</cite></div>\n" +
                    "                            <div class=\"layim-chat-text\">"+innerHTML+"</div>\n" +
                    "                        </li>";
                content1=content1+con;
                console.log(content1);
                $(".layim-chat-main ul").html(content1);

            }
            a=0;




    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = $(".layim-chat-textarea textarea").val();
        websocket.send(message);
    }
</script>
<script>
    function time(){
        var date =  new Date();
        year = date.getFullYear();
        month = date.getMonth() + 1;
        day = date.getDate();
        hours = date.getHours();
        minutes = date.getMinutes();
        seconds = date.getSeconds();
        var time=year+"/"+month+"/"+day+" "+hours+":"+minutes+":"+seconds;
        return time;
    }
    var userId=getUrlParams('u1');
    var letter_user_id=getUrlParams('u2');
    var userName="";
    var letterUserName="";
    var userImage;
    var letterUserImage;
    var content="";
    let letterContent="";
    var content1="";
layui.use('layim', function(layim){
    $.ajax({
        type: "GET",
        url: "/letter",
        data: {
            userId:userId,
            letter_user_id:letter_user_id
        },
        dataType: "json",
        success: (result, xhr, status) => {
            localStorage.removeItem("layim");
            if (result.status == 200) {
                if(userId==result.data[0].userId){
                    console.log("1111111111:"+result.data[0].letterUser.userName);
                    userName=result.data[0].user.userName;
                    letterUserName=result.data[0].letterUser.userName;
                    userImage=result.data[0].user.userImage;
                    letterUserImage=result.data[0].letterUser.userImage;
                }else if(userId==result.data[0].letter_user_id){
                    console.log("22222222222");
                    userName=result.data[0].letterUser.userName;
                    letterUserName=result.data[0].user.userName;
                    userImage=result.data[0].letterUser.userImage;
                    letterUserImage=result.data[0].user.userImage;
                }


                for(var i=0;i<result.data.length;i++){
                    if(result.data[i].userId==userId){
                        content+="<li class=\"layim-chat-mine\">\n" +
                            "                            <div class=\"layim-chat-user\"><img src=\"http://tp1.sinaimg.cn/5619439268/180/40030060651/1\"><cite><i>"+result.data[i].letter_time+"</i>"+userName+"</cite></div>\n" +
                            "                            <div class=\"layim-chat-text\">"+result.data[i].letterContent+"</div>\n" +
                            "                        </li>";
                    }else{
                        content+="<li>\n" +
                            "                            <div class=\"layim-chat-user\"><img src=\"http://tp1.sinaimg.cn/5619439268/180/40030060651/1\"><cite><i>"+result.data[i].letter_time+"</i>"+letterUserName+"</cite></div>\n" +
                            "                            <div class=\"layim-chat-text\">"+result.data[i].letterContent+"</div>\n" +
                            "                        </li>";
                    }
                }
            }else if(result.status == 100){
                userName=result.data[0].userName;
                letterUserName=result.data[1].userName;
                userImage=result.data[0].userImage;
                letterUserImage=result.data[1].userImage;
                content="";
            }
            //自定义客服窗口
            layim.config({

                brief: true //简约模式，不显示主面板
                ,init: {
                    //我的信息
                    "mine": {
                        "username": userName //我的昵称
                        ,"id": userId //我的ID
                        ,"status": "online" //在线状态 online：在线、hide：隐身
                        ,"sign": "在深邃的编码世界，做一枚轻盈的纸飞机" //我的签名
                        ,"avatar": "http://tp1.sinaimg.cn/5619439268/180/40030060651/1" //我的头像
                    }
                }
            }).chat({
                name: letterUserName //名称
                ,type: 'friend' //聊天类型
                ,avatar: 'http://tp1.sinaimg.cn/5619439268/180/40030060651/1' //头像
                ,id: -2 //定义唯一的id方便你处理信息
            });
            layim.on('sendMessage', function (data) {
                //调用socket方法，发送消息
                im.sendMsg(data);
            });
        }
    });

});
let a=0;
    $(document).on("click",".layim-chat-send",function () {
        letterContent=$(".layim-chat-textarea textarea").val();
        console.log("letterContent:"+letterContent);
        if(letterContent!=""){
            a=1;

            send();

            $.ajax({
                type: "GET",
                url: "/letter/add",
                data: {
                    userId: userId,
                    letter_user_id: letter_user_id,
                    letterContent:letterContent
                },
                dataType: "json",
                success: (result, xhr, status) => {
                    if(result.status==200){
                        alert("发送成功");
                    }else{
                        alert("发送失败");
                    }
                }
            });
            content1+="<li class=\"layim-chat-mine\">\n" +
                "                            <div class=\"layim-chat-user\"><img src=\"http://tp1.sinaimg.cn/5619439268/180/40030060651/1\"><cite><i>"+time()+"</i>"+userName+"</cite></div>\n" +
                "                            <div class=\"layim-chat-text\">"+letterContent+"</div>\n" +
                "                        </li>";
            let content2="<textarea></textarea>";
            $(".layim-chat-textarea").html(content2);
        }

    });
    var b=0;
    $(document).on("click","#a1",function () {
        if(content==null){
            alert("无历史记录");
        }
        if(b==0){
            content1=content+content1;
            b++;
        }

        $(".layim-chat-main ul").html(content1);
    });






</script>
</body>
</html>